package com.study.fileupload;

import com.study.bean.Result;
import com.study.properties.UploadFile;
import com.study.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author chenyeqing
 * @Date 2021/11/29 21:49
 */
@Slf4j
@Controller
public class FileUploadController {

    @Autowired
    private UploadFile uploadFile;


    @ResponseBody
    @RequestMapping("/singleFile/upload")
    public Result singleFileUpload(@RequestParam("myFile") MultipartFile file, Model model) {
        //判断文件是否为空
        if(file.isEmpty()){
            model.addAttribute("result_singlefile", "文件为空");
            return ResultUtil.error("文件为空");
        }

        // 上传文件的名称
        String fileName = file.getOriginalFilename();
        // 上传路径
        String filePath = uploadFile.getPath();
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            log.info("上传成功");
            return ResultUtil.success("上传成功", uploadFile.getUrl() + fileName);
        } catch (IOException e) {
            log.error(e.toString(), e);
        }
        return ResultUtil.success("上传成功", uploadFile.getUrl() + fileName);
    }

    @ResponseBody
    @RequestMapping("/multiFile/upload")
    public Result multiFileUpload(@RequestParam("myFile") MultipartFile[] files, Model model) {

        List<String> filesPath = new ArrayList<>();

        for (int i = 0; i < files.length; i++) {
            //判断文件是否为空
            if(files[i].isEmpty()){
                model.addAttribute("result_singlefile", "文件为空");
                return ResultUtil.error("文件为空");
            }

            // 上传文件的名称
            String fileName = files[i].getOriginalFilename();
            // 上传路径
            String filePath = uploadFile.getPath();
            File dest = new File(filePath + fileName);
            try {
                files[i].transferTo(dest);
                log.info("第{}个文件上传成功", (i+1));
                filesPath.add(uploadFile.getUrl() + fileName);
            } catch (IOException e) {
                log.error("上传第{}个文件失败", (i+1));
                log.error(e.toString(), e);
                return ResultUtil.error("上传第" + (i+1) + "个文件失败");
            }
        }
        return ResultUtil.success("上传成功", filesPath);
    }


}
